/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.compomics.fspike.gui;

import com.compomics.fspike.contentprovider.fastaproviders.impl.DefaultFastaProvider;
import com.compomics.fspike.contentprovider.fastaproviders.impl.NucleotideFastaProvider;
import com.compomics.fspike.contentprovider.fastaproviders.impl.UniprotFastaProvider;
import com.compomics.fspike.contentprovider.localprovider.ResourceContentProvider;
import com.compomics.fspike.gui.dialog.DialogKnownContaminants;
import com.compomics.fspike.gui.dialog.DialogUniprotContaminant;
import com.compomics.fspike.gui.dialog.DialogViewContaminant;
import com.compomics.util.gui.DummyFrame;
import com.compomics.util.gui.UtilitiesGUIDefaults;
import com.compomics.util.gui.waiting.waitinghandlers.WaitingDialog;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;

/**
 *
 * @author Kenneth
 */
public class FastaBuilderGUI extends javax.swing.JFrame {

    private DefaultFastaProvider provider;
    private static final Map<String, String> contaminationMap = new HashMap<>();
    private NCBITaxonomyViewer viewer;

    /**
     * Creates new form FastaBuilderGUI
     */
    public FastaBuilderGUI() {
        initComponents();
        initFastaBuilderGui();
    }

    private void initFastaBuilderGui() {
        // set the look and feel
        try {
            this.setIconImage(Toolkit.getDefaultToolkit().getImage(FastaBuilderGUI.class.getResource("/icons/temp_icon_gray.png")));
            UtilitiesGUIDefaults.setLookAndFeel();
        } catch (Exception ex) {
            Logger.getLogger(NCBITaxonomyViewer.class.getName()).log(Level.SEVERE, null, ex);
        }
        buttonGroup2.add(existingFastaRadioButton);
        buttonGroup2.add(translatedFastaRadioButton);
        buttonGroup2.add(taxonomyLookupRadioButton);
        existingFastaRadioButton.setSelected(true);
        existingFastaRadioButtonActionPerformed(null);
        jList1.setModel(new DefaultListModel());
        setMouseListenerToList(this);
    }

    private void setMouseListenerToList(final JFrame parent) {
        jList1.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent evt) {
                JList list = (JList) evt.getSource();
                if (evt.getClickCount() == 2) {
                    List selectedValuesList = list.getSelectedValuesList();
                    if (selectedValuesList.size() == 1) {
                        String contaminantName = (String) selectedValuesList.get(0);
                        DialogViewContaminant dialogViewContaminant = new DialogViewContaminant(jList1, contaminationMap, contaminantName, parent, true);
                        dialogViewContaminant.setLocationRelativeTo(parent);
                        dialogViewContaminant.setVisible(true);
                    }

                }
            }
        });
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup2 = new javax.swing.ButtonGroup();
        jButton5 = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        creationPanel = new javax.swing.JPanel();
        existingFastaRadioButton = new javax.swing.JRadioButton();
        translatedFastaRadioButton = new javax.swing.JRadioButton();
        taxonomyLookupRadioButton = new javax.swing.JRadioButton();
        existingFastaTextField = new javax.swing.JTextField();
        translatedFastaTextField = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jTextField4 = new javax.swing.JTextField();
        jTextField5 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        taxonomyTreeSelectedFastaTextField = new javax.swing.JTextField();
        jButton9 = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jCheckBox1 = new javax.swing.JCheckBox();
        jButton6 = new javax.swing.JButton();
        jButton7 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jButton3 = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        outputFolderTextField = new javax.swing.JTextField();
        jButton4 = new javax.swing.JButton();
        saveFastaCheckbox = new javax.swing.JCheckBox();
        jButton8 = new javax.swing.JButton();

        jButton5.setText("jButton5");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("FSpike");
        setBackground(new java.awt.Color(255, 255, 255));

        jPanel4.setBackground(new java.awt.Color(255, 255, 255));

        creationPanel.setBackground(new java.awt.Color(255, 255, 255));
        creationPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Create Spiked Fasta"));

        existingFastaRadioButton.setBackground(new java.awt.Color(255, 255, 255));
        existingFastaRadioButton.setText("By Existing Fasta");
        existingFastaRadioButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                existingFastaRadioButtonActionPerformed(evt);
            }
        });

        translatedFastaRadioButton.setBackground(new java.awt.Color(255, 255, 255));
        translatedFastaRadioButton.setText("By Translated Fasta");
        translatedFastaRadioButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                translatedFastaRadioButtonActionPerformed(evt);
            }
        });

        taxonomyLookupRadioButton.setBackground(new java.awt.Color(255, 255, 255));
        taxonomyLookupRadioButton.setText("By TaxonomyID");
        taxonomyLookupRadioButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                taxonomyLookupRadioButtonActionPerformed(evt);
            }
        });

        jButton1.setText("...");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("...");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jTextField4.setText("5");
        jTextField4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField4ActionPerformed(evt);
            }
        });

        jTextField5.setText("30");

        jLabel1.setText("-");

        jLabel2.setText("Transcript Length Length Between ");

        taxonomyTreeSelectedFastaTextField.setEditable(false);

        jButton9.setText("...");
        jButton9.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton9ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout creationPanelLayout = new javax.swing.GroupLayout(creationPanel);
        creationPanel.setLayout(creationPanelLayout);
        creationPanelLayout.setHorizontalGroup(
            creationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(creationPanelLayout.createSequentialGroup()
                .addGroup(creationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(creationPanelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(taxonomyLookupRadioButton))
                    .addGroup(creationPanelLayout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(translatedFastaRadioButton))
                    .addGroup(creationPanelLayout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(existingFastaRadioButton)))
                .addGap(32, 32, 32)
                .addGroup(creationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(creationPanelLayout.createSequentialGroup()
                        .addGroup(creationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(translatedFastaTextField)
                            .addComponent(existingFastaTextField))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(creationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jButton2, javax.swing.GroupLayout.Alignment.TRAILING)))
                    .addGroup(creationPanelLayout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(creationPanelLayout.createSequentialGroup()
                        .addComponent(taxonomyTreeSelectedFastaTextField)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton9)))
                .addContainerGap())
        );

        creationPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {existingFastaRadioButton, taxonomyLookupRadioButton, translatedFastaRadioButton});

        creationPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jTextField4, jTextField5});

        creationPanelLayout.setVerticalGroup(
            creationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(creationPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(creationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(existingFastaRadioButton)
                    .addComponent(existingFastaTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addGap(18, 18, 18)
                .addGroup(creationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(translatedFastaRadioButton)
                    .addComponent(translatedFastaTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(creationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(creationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(taxonomyLookupRadioButton)
                    .addComponent(taxonomyTreeSelectedFastaTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton9))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Add Spikes"));

        jCheckBox1.setBackground(new java.awt.Color(255, 255, 255));
        jCheckBox1.setSelected(true);
        jCheckBox1.setText("Add default contaminants");

        jButton6.setText("Add known spike");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });

        jButton7.setText("Add uniprot spike");
        jButton7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton7ActionPerformed(evt);
            }
        });

        jScrollPane1.setViewportView(jList1);

        jButton3.setText("-");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 192, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jCheckBox1))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 444, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jButton6, jButton7});

        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton6)
                .addGap(4, 4, 4)
                .addComponent(jButton7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 24, Short.MAX_VALUE)
                .addComponent(jCheckBox1))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jButton3)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addGap(2, 2, 2))
        );

        jPanel3.setBackground(new java.awt.Color(255, 255, 255));
        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Output to ..."));

        jLabel5.setText("Output Folder : ");

        jButton4.setText("...");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        saveFastaCheckbox.setBackground(new java.awt.Color(255, 255, 255));
        saveFastaCheckbox.setSelected(true);
        saveFastaCheckbox.setText("Save clean fasta");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(outputFolderTextField)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton4))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(saveFastaCheckbox)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(outputFolderTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton4)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(saveFastaCheckbox)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jButton8.setText("Process Fasta");
        jButton8.setOpaque(false);
        jButton8.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton8ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(creationPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jButton8)))
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(creationPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton8)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        DialogKnownContaminants newDialog = new DialogKnownContaminants(jList1, contaminationMap, this, true);
        newDialog.setVisible(true);

    }//GEN-LAST:event_jButton6ActionPerformed


    private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed

        if (outputFolderTextField.getText().isEmpty()) {
            jButton4ActionPerformed(evt);
            if (outputFolderTextField.getText().isEmpty()) {
                JOptionPane.showMessageDialog(this,
                        "Outputfolder was not specified.",
                        "Error",
                        JOptionPane.ERROR_MESSAGE);
                return;
            }
        }
        final WaitingDialog dialog = new WaitingDialog(new DummyFrame("F-Spike", "/icons/temp_icon_gray.png"),
                Toolkit.getDefaultToolkit().getImage(FastaBuilderGUI.class.getResource("/icons/temp_icon_gray.png")),
                Toolkit.getDefaultToolkit().getImage(FastaBuilderGUI.class.getResource("/icons/temp_icon_orange.png")),
                false, ResourceContentProvider.getTips(), "Spiking fasta", "F-Spike", "0.0.2", true);
        ((WaitingDialog) dialog).setCloseDialogWhenImportCompletes(false, false);
        ((WaitingDialog) dialog).setLocationRelativeTo(null);
        Point tempLocation = ((WaitingDialog) dialog).getLocation();
        ((WaitingDialog) dialog).setLocation((int) tempLocation.getX() + 30, (int) tempLocation.getY() + 30);

        final SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {

            @Override
            protected Void doInBackground() {
                process();
                return null;
            }

            @Override
            protected void done() {
                dialog.appendReport("Done !", true, false);
            }

            //todo split this in smaller, maintainable sections
            private void process() {
                try {
                    File outputFolder = new File(outputFolderTextField.getText());
                    if (outputFolderTextField.getText().isEmpty()) {
                        String suggestedOutputFolder = provider.getCleanFastaFile().getParent();
                        dialog.appendReport("Output folder not specified, setting to " + suggestedOutputFolder, true, true);
                        outputFolderTextField.setText(suggestedOutputFolder);
                    }
                    dialog.appendReport("Selecting fasta provider...", true, false);
                    if (taxonomyLookupRadioButton.isSelected()) {
                        Thread.sleep(100);
                        if (taxonomyTreeSelectedFastaTextField.getText().isEmpty()) {
                            JOptionPane.showMessageDialog(null,
                                    "TaxonomyID to download was not specified.",
                                    "Error",
                                    JOptionPane.ERROR_MESSAGE);
                            return;
                        }
                        provider = new UniprotFastaProvider(taxonomyTreeSelectedFastaTextField.getText(), outputFolder);
                    } else if (translatedFastaRadioButton.isSelected()) {
                        Thread.sleep(100);
                        int minPep = Integer.parseInt(jTextField4.getText());
                        int maxPep = Integer.parseInt(jTextField5.getText());
                        File inputFile = new File(translatedFastaTextField.getText());
                        if (translatedFastaTextField.getText().isEmpty()) {
                            JOptionPane.showMessageDialog(null,
                                    "Fasta to translate was not specified.",
                                    "Error",
                                    JOptionPane.ERROR_MESSAGE);
                            return;
                        }
                        if (jTextField4.getText().isEmpty() || jTextField5.getText().isEmpty()) {
                            JOptionPane.showMessageDialog(null,
                                    "Transcript length was not specified.",
                                    "Error",
                                    JOptionPane.ERROR_MESSAGE);
                            return;
                        }

                        provider = new NucleotideFastaProvider(inputFile, minPep, maxPep);
                    } else {
                        Thread.sleep(100);
                        File inputFile = new File(existingFastaTextField.getText());
                        if (existingFastaTextField.getText().isEmpty() || jTextField5.getText().isEmpty()) {
                            JOptionPane.showMessageDialog(null,
                                    "Fasta was not specified.",
                                    "Error",
                                    JOptionPane.ERROR_MESSAGE);
                            return;
                        }
                        provider = new DefaultFastaProvider(inputFile);
                    }
                    provider.setWaitingDialog(dialog);
                    dialog.increasePrimaryProgressCounter(20);
                    //generate the fasta file without contaminants
                    dialog.appendReport("\t\tdone", false, true);
                    dialog.appendReport("Getting clean fasta file...", true, true);
                    File cleanFastaFile;
                    try {
                        cleanFastaFile = provider.getCleanFastaFile();
                    } catch (Exception e) {
                        dialog.appendReport(e.toString(), true, true);
                        dialog.setRunFinished();
                        return;
                    }
                    dialog.appendReport("Validating generated protein fasta...", true, false);
                    if (cleanFastaFile.length() == 0) {
                        cleanFastaFile.delete();
                        //delete on exit because it will still be in use at this point...
                        new File(cleanFastaFile.getAbsolutePath().replace(".fasta", "_spiked.fasta")).deleteOnExit();
                        new File(cleanFastaFile.getAbsolutePath().replace(".fasta", "_spiked.fasta.cui")).delete();
                        dialog.appendReport("An error has occurred : fasta is empty...", true, false);
                        dialog.setRunFinished();
                        JOptionPane.showMessageDialog(null,
                                "The resulting fasta was empty ! ",
                                "Error",
                                JOptionPane.ERROR_MESSAGE);
                        return;

                    }
                    dialog.increasePrimaryProgressCounter(20);
                    dialog.appendReport("\t\tdone", false, true);
                    //add contaminants
                    if (jCheckBox1.isSelected()) {
                        Thread.sleep(100);
                        provider.addDefaultSpikes();
                        dialog.appendReport("\t\tdone", false, true);
                    }
                    dialog.increasePrimaryProgressCounter(20);
                    dialog.appendReport("Adding selected spikes...", true, false);
                    provider.addSpikes(contaminationMap);
                    dialog.appendReport("\t\tdone", false, true);
                    dialog.increasePrimaryProgressCounter(20);
                    //save output
                    File outputFile = new File(outputFolder, provider.getContaminatedFastaFile().getName());
                    dialog.appendReport("Saving spiked fasta...", true, false);
                    provider.saveContaminatedFasta(outputFile);
                    dialog.appendReport("\t\tdone", false, true);
                    if (existingFastaRadioButton.isSelected()) {
                        if (saveFastaCheckbox.isSelected()) {
                            Thread.sleep(100);
                            dialog.appendReport("Saving clean fasta...", true, false);
                            provider.saveCleanFasta(new File(outputFolder, provider.getCleanFastaFile().getName()));
                            dialog.appendReport("\t\tdone", false, true);
                        } else {
                            provider.getCleanFastaFile().delete();
                        }
                    }
                    //delete cui file
                    new File(outputFile.getAbsolutePath() + ".cui").delete();
                    dialog.increasePrimaryProgressCounter(20);
                    Thread.sleep(100);
                } catch (Exception ex) {
                    Logger.getLogger(FastaBuilderGUI.class.getName()).log(Level.SEVERE, null, ex);
                }
                dialog.setRunFinished();
            }

        };
        Thread monitorCancellingThread = new Thread(new Runnable() {

            @Override
            public void run() {
                while (!dialog.isRunCanceled() && !worker.isDone() && !dialog.isRunFinished() && !worker.isCancelled()) {
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(FastaBuilderGUI.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                if (dialog.isRunCanceled()) {
                    dialog.appendReport("Generating spiked fasta cancelled", true, true);
                } else if (dialog.isRunFinished()) {
                    dialog.appendReport("Finished spikeing fasta", true, true);
                }
            }
        });
        this.setIconImage(Toolkit.getDefaultToolkit().getImage(FastaBuilderGUI.class.getResource("/icons/temp_icon_orange.png")));
        monitorCancellingThread.start();
        worker.execute();
        dialog.setVisible(true); // will block but with a responsive GUI
        while (!worker.isCancelled() && !worker.isDone()) {
            try {
                //TODO make this nicer
                Thread.sleep(100);
            } catch (InterruptedException ex) {
                Logger.getLogger(FastaBuilderGUI.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        this.setIconImage(Toolkit.getDefaultToolkit().getImage(FastaBuilderGUI.class.getResource("/icons/temp_icon_gray.png")));
    }//GEN-LAST:event_jButton8ActionPerformed


    private void existingFastaRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_existingFastaRadioButtonActionPerformed
        existingFastaTextField.setEnabled(true);
        jButton1.setEnabled(true);
        translatedFastaTextField.setEnabled(false);
        taxonomyTreeSelectedFastaTextField.setEnabled(false);
        jButton2.setEnabled(false);
        jTextField4.setEnabled(false);
        jTextField5.setEnabled(false);
        jButton9.setEnabled(false);
    }//GEN-LAST:event_existingFastaRadioButtonActionPerformed

    private void translatedFastaRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_translatedFastaRadioButtonActionPerformed
        existingFastaTextField.setEnabled(false);
        jButton1.setEnabled(false);
        translatedFastaTextField.setEnabled(true);
        jButton2.setEnabled(true);
        taxonomyTreeSelectedFastaTextField.setEnabled(false);
        jTextField4.setEnabled(true);
        jTextField5.setEnabled(true);
        jButton9.setEnabled(false);
    }//GEN-LAST:event_translatedFastaRadioButtonActionPerformed

    private void taxonomyLookupRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_taxonomyLookupRadioButtonActionPerformed
        existingFastaTextField.setEnabled(false);
        jButton1.setEnabled(false);
        translatedFastaTextField.setEnabled(false);
        jButton2.setEnabled(false);
        taxonomyTreeSelectedFastaTextField.setEnabled(true);
        jTextField4.setEnabled(false);
        jTextField5.setEnabled(false);
        jButton9.setEnabled(true);
    }//GEN-LAST:event_taxonomyLookupRadioButtonActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        JFileChooser fc = new JFileChooser();
        // Set the text
        fc.setApproveButtonText("Select");
        int returnVal = fc.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            try {
                existingFastaTextField.setText(file.getAbsolutePath());
            } catch (Exception ex) {
                Logger.getLogger(FastaBuilderGUI.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        JFileChooser fc = new JFileChooser();
        fc.setApproveButtonText("Select");
        int returnVal = fc.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            try {
                translatedFastaTextField.setText(file.getAbsolutePath());
            } catch (NumberFormatException ex) {
                Logger.getLogger(FastaBuilderGUI.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jTextField4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField4ActionPerformed

    }//GEN-LAST:event_jTextField4ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        JFileChooser fc = new JFileChooser();
        fc.setApproveButtonText("Select");
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int returnVal = fc.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            try {
                outputFolderTextField.setText(file.getAbsolutePath());
            } catch (Exception ex) {
                Logger.getLogger(FastaBuilderGUI.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
        DialogUniprotContaminant newDialog = new DialogUniprotContaminant(jList1, contaminationMap, this, true);
        newDialog.setVisible(true);
    }//GEN-LAST:event_jButton7ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        DefaultListModel model = (DefaultListModel) jList1.getModel();
        for (Object anEntry : jList1.getSelectedValuesList()) {
            model.removeElement(anEntry);
            contaminationMap.remove(anEntry.toString());
        }
        jList1.setModel(model);
        jList1.revalidate();
        jList1.repaint();
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed
        try {
            if (viewer == null) {
                viewer = new NCBITaxonomyViewer(taxonomyTreeSelectedFastaTextField);
                viewer.setLocationRelativeTo(this);
            }
            viewer.setVisible(true);
        } catch (IOException ex) {
            Logger.getLogger(FastaBuilderGUI.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton9ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FastaBuilderGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FastaBuilderGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FastaBuilderGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FastaBuilderGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                FastaBuilderGUI fastaBuilderGUI = new FastaBuilderGUI();
                fastaBuilderGUI.setLocationRelativeTo(null);
                fastaBuilderGUI.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup2;
    private javax.swing.JPanel creationPanel;
    private javax.swing.JRadioButton existingFastaRadioButton;
    private javax.swing.JTextField existingFastaTextField;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JButton jButton7;
    private javax.swing.JButton jButton8;
    private javax.swing.JButton jButton9;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JList jList1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;
    private javax.swing.JTextField outputFolderTextField;
    private javax.swing.JCheckBox saveFastaCheckbox;
    private javax.swing.JRadioButton taxonomyLookupRadioButton;
    private javax.swing.JTextField taxonomyTreeSelectedFastaTextField;
    private javax.swing.JRadioButton translatedFastaRadioButton;
    private javax.swing.JTextField translatedFastaTextField;
    // End of variables declaration//GEN-END:variables
}
